import configparser
import os
import sys
from datetime import datetime
import clr
import uuid
import json
import time
import requests
import logging
import traceback
import threading
import itertools
import multiprocessing
from typing import Any
from typing import List
from typing import Union
from typing import Optional


base_dirs = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
dll_dirs: str = base_dirs + os.sep + "library" + os.sep + "Library.dll"
exec("clr.AddReference(dll_dirs)")
exec("from Library import *")


class WorkWS04AIMAGE(threading.Thread):
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(WorkWS04AIMAGE, cls).__new__(cls)
        return cls._instance

    def __init__(self, host: str = "192.168.10.80", port: int = 8501):
        super(WorkWS04AIMAGE, self).__init__()
        self.daemon = True
        self.interval = 0.6
        self.connect = eval("NanoSerialOverTcp('{}', {})".format(host, port))
        self.IsNet: bool = False
        self.ConnectError: int = 0
        self.UPLOAD: bool = False
        self.URL: Union[str, None] = None
        self.PATH0: Union[str, None] = None
        self.PATH1: Union[str, None] = None

    def run(self):
        config_name: str = base_dirs + os.sep + "image.ini"

        parser = configparser.ConfigParser()
        parser.read(filenames=config_name, encoding="utf-8")
        self.UPLOAD: bool = parser.getboolean(section="CONF", option="UPLOAD")
        self.URL: str = parser.get(section="CONF", option="URL")
        self.PATH0: str = parser.get(section="CONF", option="PATH0")
        self.PATH1: str = parser.get(section="CONF", option="PATH1")

        while True:
            start: float = time.perf_counter()
            if self.connect.IsConnect() is True:
                self.IsNet = True
                self.ConnectError = 0
            else:
                self.IsNet = False
                self.ConnectError = self.ConnectError + 1
            # noinspection PyBroadException
            try:
                if self.ConnectError > 8:
                    sys.exit(-1)
            except Exception as e:
                logging.error(msg=traceback.print_exc())

            # MES与PLC之间数据交互逻辑代码
            # noinspection PyBroadException
            try:
                r_parm: dict = {
                    "DM8192": "Short",
                    "DM1150": "String"
                }
                data_str_tq_main = self.connect.ReadAll(json.dumps(r_parm))
                plc: dict = json.loads(data_str_tq_main)

                if plc.get("DM8192") >= 1:
                    if len(plc.get("DM1150")) == 0:
                        time.sleep(0.16)
                        plc["DM1150"] = self.connect.ReadString("DM1150")
                    now = datetime.now()
                    temp_array = [
                        str(now.year), str(now.month).zfill(2), str(now.day).zfill(2),
                        str(now.hour).zfill(2), str(now.minute).zfill(2), str(now.second).zfill(2)
                    ]
                    name = "".join(temp_array)
                    filename = "{}.JPG".format(name) if len(plc["DM1150"]) <= 0 else "{}.JPG".format(plc["DM1150"])

                    if self.UPLOAD is True and os.path.exists(self.PATH0) and os.path.exists(self.PATH1):
                        with open(self.PATH0, 'rb') as file0:
                            image0 = file0.read()
                        with open(self.PATH1, 'rb') as file1:
                            image1 = file1.read()
                        http_parm = {'image0': (filename, image0), 'image1': (filename, image1)}
                        requests.post(url=self.URL, files=http_parm, timeout=4.8)

                    self.connect.WriteShort("DM8192", 0)

            except Exception as e:
                logging.error(msg="UPDATE:= {}".format(traceback.print_exc()))
                sys.exit(-1)

            elapsed: float = time.perf_counter() - start
            time.sleep(max(0.0, self.interval - elapsed))


